package com.mpgame.database.mysql.service.verify;

import java.sql.Timestamp;

import org.apache.ibatis.session.SqlSession;

import com.mpgame.database.mysql.mapper.verify.AccountMapper;
import com.mpgame.database.mysql.model.verify.Account;
import com.mpgame.database.mysql.utils.MyBatisUtil;
import com.mpgame.utils.Log;

public class AccountService {
    public int createAccount(Account account, String last_login_ip){
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            account.setCreatedAt(new Timestamp(System.currentTimeMillis()));
            account.setLastLoginAt(new Timestamp(System.currentTimeMillis()));
            account.setLastLoginIp(last_login_ip);
            int res = mapper.insert(account);

            sqlSession.commit();

            if(res > 0){
                Log.info("创建账号成功");
                return account.getId();
            }
            else{
                Log.err("创建账号失败");
                return 0;
            }
        }catch(Exception e){
            Log.err("创建账号异常" + e.getMessage());
            throw new RuntimeException("创建账号异常", e);
        }finally{
            if(sqlSession != null){
                sqlSession.close();
            }
        }
    }

    public Account getAccount(String username){
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            Account account = mapper.selectByUsername(username);
            
            if(account != null){
                Log.info("成功找到账号，" + username);
            }
            else{
                Log.warn("未找到此账号，" + username);
            }
            return account;
        }catch(Exception e){
            Log.err("获取账号失败" + e.getMessage());
            throw new RuntimeException("获取账号异常", e);
        }finally{
            if(sqlSession != null){
                sqlSession.close();
            }
        }
    }

    public int updateLastLogin(String username, Timestamp last_login_at, String last_login_ip){
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            int affectedRows = mapper.updateLastLogin(username, last_login_at, last_login_ip);
            sqlSession.commit();
            return affectedRows;
        }catch(Exception e){
            Log.err("更新最后登录信息失败：" + e.getMessage());
            throw new RuntimeException("更新最后登录信息失败：" + e.getMessage());
        }finally{
            if(sqlSession != null){
                sqlSession.close();
            }
        }
    }
}
